import {
  Breadcrumb,
  Button,
  Card,
  Form,
  Input,
  message,
  Modal,
  Radio,
  Select,
  Space,
  Upload,
} from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import {
  addArticleApi,
  getArticleDetailApi,
  editArticleApi,
} from 'api/article';
import { getChannelsApi } from 'api/channel';
import { PlusOutlined } from '@ant-design/icons';
import { baseURL } from 'utils/request';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import styles from './index.module.scss';
// import history from 'utils/history';
import { getToken } from 'utils/storage';
const { Option } = Select;

export default function ArticlePublish(props) {
  // console.log(props);

  const [channels, setChannels] = useState([]);
  // 图片上传相关
  const [type, setType] = useState(1);
  const [fileList, setFileList] = useState([]);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewUrl, setPreviewUrl] = useState('');

  const [form] = Form.useForm();

  const editId = props.match.params.id ? props.match.params.id : '';
  const draftRef = useRef(false);
  useEffect(() => {
    if (editId) {
      console.log(47, editId);
      getArtcleDetail(editId);
    }
    getChannels();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  //获取频道
  const getChannels = async () => {
    const res = await getChannelsApi();
    setChannels(res.data.channels);
  };
  //获取文章详情
  const getArtcleDetail = async (id) => {
    const res = await getArticleDetailApi(id);
    console.log(res);

    const fileList = res.data.cover.images.map((item) => ({ url: item }));
    setFileList(fileList);
    setType(res.data.cover.type);
    form.setFieldsValue({
      ...res.data,
      type: res.data.cover.type,
    });
  };

  //改变图片类型
  const changImageType = (e) => {
    setType(e.target.value);
  };
  //切换图片类型时，上传列表页相应变化
  const showFileList = fileList.filter((iten, index) => {
    if (type === 0) {
      return false;
    }
    if (fileList.length > type) {
      return index === 0;
    }
    return true;
  });
  // 图片上传相关
  const handleCancel = () => setPreviewVisible(false);

  const handleChange = ({ file, fileList }) => {
    console.log(file);
    setFileList(fileList);
  };
  // 情况1：如果 fileList 是将来后端回显的，通过 url 就能够访问到
  // 情况2：如果 fileList 的文件是上传的，需要通过 file.response.data.url 获取
  //预览
  const handlePreview = (file) => {
    console.log(file);
    const url = file.url || file.response.data.url;
    setPreviewVisible(true);
    setPreviewUrl(url);
  };

  //校验
  const beforeUpload = (file) => {
    console.log(file);
    if (file.size > 1024 * 1024) {
      message.warn('图片大小不能超过1m', 2);
      return Upload.LIST_IGNORE;
    }
    if (
      !['image/gif', 'image/png', 'image/jpg', 'image/jpeg'].includes(file.type)
    ) {
      message.warn('图片格式要求为jpg,jpeg,png,gif', 1);
      return Upload.LIST_IGNORE;
    }
    return true;
  };
  //发布文章
  const onFinish = async (values) => {
    console.log(values);
    if (showFileList.length !== type) {
      return message.warn('图片数量不对！', 1);
    }
    //回显时的fileList的数据结构跟原来的结构不一样，需要兼容两种情况
    const coverUrl =
      showFileList.length &&
      showFileList.map((item) => item.url || item.response.data.url);
    if (editId) {
      //编辑
      const res = await editArticleApi({
        id: editId,
        draft: draftRef.current,
        ...values,
        cover: { type, images: coverUrl },
      });
      if (res.message === 'OK') {
        message.success('编辑文章成功！', 1);
        // history.push('/list');
      }
    } else {
      //新增
      const res = await addArticleApi({
        draft: draftRef.current,
        ...values,
        cover: { type, images: coverUrl },
      });
      if (res.message === 'OK') {
        message.success('发布文章成功！', 1);
        // history.push('/list');
      }
    }
    props.history.push('/list');
  };

  return (
    <div className={styles['articlePublish']}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              {editId ? '编辑文章' : '发布文章'}
            </Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          form={form}
          size="large"
          labelCol={{ span: 4 }}
          initialValues={{
            type: 1,
            title: '',
            channel_id: 0,
            content: '',
          }}
          onFinish={onFinish}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择频道' }]}
          >
            <Select style={{ width: 200 }}>
              {channels.map((item) => (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={changImageType}>
                <Radio value={0}>无图</Radio>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item>
              {/* 图片上传组件 */}
              <div>
                {type !== 0 && (
                  <Upload
                    action={`${baseURL}/v1_0/upload`}
                    headers={{ Authorization: `Bearer ${getToken()}` }}
                    listType="picture-card"
                    name="image"
                    fileList={showFileList}
                    onPreview={handlePreview}
                    onChange={handleChange}
                    beforeUpload={beforeUpload}
                  >
                    {fileList.length >= type ? null : <PlusOutlined />}
                  </Upload>
                )}
              </div>
              {/* 预览 */}
              <Modal
                visible={previewVisible}
                title="图片预览"
                footer={null}
                onCancel={handleCancel}
              >
                <img alt="example" style={{ width: '100%' }} src={previewUrl} />
              </Modal>
            </Form.Item>
          </Form.Item>

          <Form.Item
            label="内容"
            name="content"
            rules={[
              { required: true, message: '请输入文章内容' },
              {
                message: '请输入文章内容',
                validator: (_, value) => {
                  if (value === '<p><br></p>') {
                    return Promise.reject(new Error('请输入文章内容'));
                  }
                  return Promise.resolve();
                },
              },
            ]}
          >
            <ReactQuill
              className="ql-editor"
              theme="snow"
              placeholder="请输入文章内容..."
            />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                {editId ? '编辑文章' : '发布文章'}
              </Button>
              <Button
                htmlType="submit"
                onClick={() => (draftRef.current = true)}
              >
                存入草稿
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
}
